#include "SeqList.h"
#include <assert.h>
#define _CRT_SECURE_NO_WARNINGS

void SLInit(SL* s)
{
	s->a = (SLDatatype*)malloc(sizeof(SLDatatype) * 4);
	if (s->a == NULL) return;
	s->capacity = 4;
	s->size = 0;
}

static int enLargerRoom(SL* s)
{
	s->a = (SLDatatype*)realloc(s->a, sizeof(SLDatatype) * s->capacity * 2);
	if (s->a == NULL) return 1;
	s->capacity *= 2;
	return 0;
}

void SLPrint(SL* s)
{
	for (int i = 0; i < s->size; i++)
	{
		printf("%d ", s->a[i]);
	}
	printf("\n");
}

void SLDestroy(SL* s)
{
	if (s->a)
		free(s->a);
	s->a = NULL;
	s->capacity = 0;
	s->size = 0;
}


void SLPushFront(SL* s, SLDatatype x)
{
	if (s->capacity == s->size && enLargerRoom(s)) return;
	int end = s->size;
	while (end-1>=0)
	{
		s->a[end] = s->a[end - 1];
		end--;
	}
	s->a[0] = x;
	s->size++;
}

void SLPopBack(SL* s)
{
	if (s->size >= 0)
	{
		s->size--;
	}
}

void SLPopFront(SL* s)
{
	if (s->size >= 0)
	{
		int start = 0;
		while (start+1<=s->size-1)
		{
			s->a[start] = s->a[start + 1];
			start++;
		}
		s->size--;
	}
}

void SLInsert(SL* s, int pos, SLDatatype x)
{
	assert(pos >= 0 && pos <= s->size);
	int end = s->size;
	while (end - 1 >= pos)
	{
		s->a[end] = s->a[end - 1];
		end--;
	}
	s->a[pos] = x;
	s->size++;
}

void SLErase(SL* s, int pos)
{
	assert(pos >= 0 && pos <= s->size);
	int start = pos;
	while (start+1<=s->size-1)
	{
		s->a[start] = s->a[start + 1];
		start++;
	}
	s->size--;
}

int SLFind(SL* s, SLDatatype x)
{
	for (int i = 0; i < s->size; i++)
	{
		if (s->a[i] == x)
			return i;
	}
	return -1;
}


void SLPushBack(SL* s, SLDatatype x)
{
	if (s->capacity == s->size && enLargerRoom(s)) return;
	s->a[s->size++] = x;
}

